﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Resources;
using System.Reflection;

namespace UserInterface
{
    using BusinessLogicLayer;
    using BusinessObjectLayer;
    using System.Net;
    using System.IO;
    using System.Collections.Generic;
    using BusinessLogicLibrary;
    using JntMsgBox;

    public partial class ShowGalleryUI : Form
    { 
        private int _numberPreviewImages = 1000;
        private int _imageSize = 100;
        private int _currentStartImageIndex = 0;
        private int _currentEndImageIndex = 0;
        private ResourceManager _ResourceManager = new ResourceManager("UserInterface.Properties.Resources", Assembly.GetExecutingAssembly());
        ExceptionHandlerBOL _ExceptionHandlerBOL;
        string localDirectory;
        string serverDirectory;

        string UpdateText;
        string DeleteText;
        string UpdateConfirmation;
        string DeleteConfirmation;

        private AccessMode _AccessMode;
        public ShowGalleryUI(AccessMode accessMode)
        {
            InitializeComponent();
            newGalleryButton.Enabled = (accessMode != AccessMode.Read);
            localDirectory = string.Format("{0}/Gallery", ServerBLL.GetStringValue("TempPath"));
            serverDirectory = string.Format("{0}/Thumbnails", ServerBLL.GetStringValue("GalleryPath"));
        }
        private void closeForm()
        {
            this.Close();
        }
        private void newGalleryButton_Click(object sender, EventArgs e)
        {
            try
            {
                new EditGalleryUI().ShowDialog();
            }
            catch (Exception exception)
            {
                _ExceptionHandlerBOL = ExceptionHandlerBLL.HandleException(exception);
                messageTitleLabel.ForeColor = Color.Red;
                messageTitleLabel.Text = _ExceptionHandlerBOL.Title;
            }
        }
        private void ShowGallery_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                closeForm();
        }
        private void messageTitleLabel_Click(object sender, EventArgs e)
        {
            if (_ExceptionHandlerBOL != null)
                new ExceptionHandlerUI(_ExceptionHandlerBOL).ShowDialog();
            _ExceptionHandlerBOL = null;
        }
        private void ShowGalleryUI_Load(object sender, EventArgs e)
        {
            try
            {
                DownloadFiles();
                SetFiles();              
            }
            catch (Exception exception)
            {
                _ExceptionHandlerBOL = ExceptionHandlerBLL.HandleException(exception);
                messageTitleLabel.ForeColor = Color.Red;
                messageTitleLabel.Text = _ExceptionHandlerBOL.Title;
            }
        }
        private void SetFiles()
        {
            try
            {
                if (_numberPreviewImages == 1)
                {
                    _currentStartImageIndex = 0;
                    _currentEndImageIndex = 1;
                }
                else
                {
                    _currentEndImageIndex = _currentStartImageIndex + _numberPreviewImages - 1;
                }
                LoadImages();
            }
            catch (Exception exception)
            {
                _ExceptionHandlerBOL = ExceptionHandlerBLL.HandleException(exception);
                messageTitleLabel.ForeColor = Color.Red;
                messageTitleLabel.Text = _ExceptionHandlerBOL.Title;
            }
        }
        private void DownloadFiles()
        {
            try
            {                                

                //if (Directory.Exists(path))
                //    Directory.Delete(path, true);
                if (!Directory.Exists(localDirectory))
                    Directory.CreateDirectory(localDirectory);
                FileBOL _FileBOL = new FileBOL(serverDirectory);
                new FileBLL().DownloadFiles(_FileBOL);
            }
            catch (Exception exception)
            {
                _ExceptionHandlerBOL = ExceptionHandlerBLL.HandleException(exception);
                messageTitleLabel.ForeColor = Color.Red;
                messageTitleLabel.Text = _ExceptionHandlerBOL.Title;
            }
        }
        private void LoadImages()
        {
            try
            {            
                if (this.WindowState == FormWindowState.Minimized)
                {
                    return;
                }
                string path = string.Format("{0}/Gallery", ServerBLL.GetStringValue("TempPath"));

                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                FileInfo[] jpgFiles = directoryInfo.GetFiles("*.jpg");
                FileInfo[] bmpFiles = directoryInfo.GetFiles("*.bmp");
                FileInfo[] pngFiles = directoryInfo.GetFiles("*.png");
                FileInfo[] gifFiles = directoryInfo.GetFiles("*.gif");
                var fileList = new List<FileInfo>();
                fileList.AddRange(jpgFiles);
                fileList.AddRange(bmpFiles);
                fileList.AddRange(pngFiles);
                fileList.AddRange(gifFiles);
                FileInfo[] allFiles = fileList.ToArray();                
                dataViewImages.Rows.Clear();
                dataViewImages.Columns.Clear();

                int numColumnsForWidth = (dataViewImages.Width - 10) / (_imageSize + 20);
                int numRows = 0;

                int numImagesRequired = 0;

                if (_currentEndImageIndex > allFiles.Length)
                {
                    if (_currentStartImageIndex == 0)
                    {
                        numImagesRequired = allFiles.Length;
                    }
                    else
                    {
                        numImagesRequired = (_currentEndImageIndex - _currentStartImageIndex) - (_currentEndImageIndex - allFiles.Length);
                    }
                }
                else
                {
                    numImagesRequired = _currentEndImageIndex - _currentStartImageIndex;
                }

                numRows = numImagesRequired / numColumnsForWidth;
                if (numImagesRequired % numColumnsForWidth > 0)
                {
                    numRows += 1;
                }
                if (numImagesRequired < numColumnsForWidth)
                {
                    numColumnsForWidth = numImagesRequired;
                }

                int numGeneratedCells = numRows * numColumnsForWidth;
                for (int index = 0; index < numColumnsForWidth; index++)
                {
                    DataGridViewImageColumn dataGridViewColumn = new DataGridViewImageColumn();

                    dataViewImages.Columns.Add(dataGridViewColumn);
                    dataViewImages.Columns[index].Width = _imageSize + 20;
                }
                for (int index = 0; index < numRows; index++)
                {
                    dataViewImages.Rows.Add();
                    dataViewImages.Rows[index].Height = _imageSize + 20;
                }
                int columnIndex = 0;
                int rowIndex = 0;
                for (int index = _currentStartImageIndex; index < _currentStartImageIndex + numImagesRequired; index++)
                {
                    Image image = Helper.ResizeImage(allFiles[index].FullName, _imageSize, _imageSize, false);
                    dataViewImages.Rows[rowIndex].Cells[columnIndex].Value = image;
                    dataViewImages.Rows[rowIndex].Cells[columnIndex].ToolTipText = Path.GetFileName(allFiles[index].FullName);
                    if (columnIndex == numColumnsForWidth - 1)
                    {
                        rowIndex++;
                        columnIndex = 0;
                    }
                    else
                    {
                        columnIndex++;
                    }
                }
                if (numGeneratedCells > numImagesRequired)
                {
                    for (int index = 0; index < numGeneratedCells - numImagesRequired; index++)
                    {
                        DataGridViewCellStyle dataGridViewCellStyle = new DataGridViewCellStyle();
                        dataGridViewCellStyle.NullValue = null;
                        dataGridViewCellStyle.Tag = "BLANK";
                        dataViewImages.Rows[rowIndex].Cells[columnIndex + index].Style = dataGridViewCellStyle;
                    }
                }            
            }
            catch (Exception exception)
            {
                _ExceptionHandlerBOL = ExceptionHandlerBLL.HandleException(exception);
                messageTitleLabel.ForeColor = Color.Red;
                messageTitleLabel.Text = _ExceptionHandlerBOL.Title;
            }
        }      
        private void trackBarImageSize_Scroll(object sender, EventArgs e)
        {
            if (trackBarImageSize.Value == 0)
            {
                _imageSize = 50;
            }
            else
            {
                _imageSize = 50 * (trackBarImageSize.Value + 1);
            }
            LoadImages();
        }
        private void GetDeleteConfirmtion()
        {
            try
            {
                SetResourceManager();
                JntMsgBoxFarsi _JntMsgBoxFarsi = new JntMsgBoxFarsi();
                DialogResult result = _JntMsgBoxFarsi.Show(DeleteConfirmation, DeleteText, JntStyle.YesNo);
                if (result == DialogResult.No)
                    return;
                string imageName =  dataViewImages.SelectedCells[0].ToolTipText;
                FileBOL _FileBOL = new FileBOL(string.Format("{0}/{1}",localDirectory,imageName),string.Format("{0}/{1}", serverDirectory, imageName),false);
                FileBLL.Delete(_FileBOL);
                LoadImages();
            }
            catch (Exception exception)
            {
                _ExceptionHandlerBOL = ExceptionHandlerBLL.HandleException(exception);
                messageTitleLabel.ForeColor = Color.Red;
                messageTitleLabel.Text = _ExceptionHandlerBOL.Title;
            }
            finally { }
        }
        private void SetResourceManager()
        {
            try
            {
                UpdateText = _ResourceManager.GetString("Update");
                DeleteText = _ResourceManager.GetString("Delete");
                UpdateConfirmation = _ResourceManager.GetString("UpdateConfirmation");
                DeleteConfirmation = _ResourceManager.GetString("DeleteConfirmation");
            }
            catch (Exception exception)
            {
                _ExceptionHandlerBOL = ExceptionHandlerBLL.HandleException(exception);
                messageTitleLabel.ForeColor = Color.Red;
                messageTitleLabel.Text = _ExceptionHandlerBOL.Title;
            }
        }
        private void dataViewImages_DoubleClick(object sender, EventArgs e)
        {
            GetDeleteConfirmtion();
        }
    }
}
